package com.kafka.xiang;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


public class Swing extends JFrame {

    private JTextArea responseTextArea;
    private JTextField kafkaServerField;
    private JTextField connectCountField;
    private JTextField waitingTimeField;
    private int intListeningActive=0;
    private TrayIcon trayIcon = null;
    private SystemTray tray = SystemTray.getSystemTray(); // 创建系统托盘


    public Swing() {
        super("ITestAgent");
        System.setProperty("file.encoding","UTF-8");
        UIManager.put("OptionPane.buttonFont",new Font("SimSun",Font.PLAIN,12));//中文字体支持

        ImageIcon inactiveIcon = new ImageIcon("./demo/src/main/resources/static/image/fail.jpg");//这个也要变化
        this.setIconImage(inactiveIcon.getImage());
        setTray();
        responseTextArea = new JTextArea(10, 40);
        responseTextArea.setEditable(false);
        try {
            // 10s休息,等待后台连接2s后再查询连接状况
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            // 处理中断异常，如果需要的话
        }
        check();//开机自动查询连接状况
        JButton getRequestButton = new JButton("连接服务");
        getRequestButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                check();
                setTray();
            }
        });
        JButton stopButton = new JButton("停止测试");
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stop();
                setTray();
            }
        });

        // Create components
        kafkaServerField = new JTextField(20);
        connectCountField = new JTextField(5);
        waitingTimeField = new JTextField(5);
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveYaml();
            }
        });

        // Create layout
        JPanel panel = new JPanel(new GridLayout(1, 8));
        panel.add(new JLabel("服务器ip及端口",SwingConstants.CENTER));
        panel.add(kafkaServerField);
        panel.add(new JLabel("重新连接次数",SwingConstants.CENTER));
        panel.add(connectCountField);
        panel.add(new JLabel("连接等待时间/s",SwingConstants.CENTER));
        panel.add(waitingTimeField);
        panel.add(saveButton);

        // 将按钮放入一个新的面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(getRequestButton);
        buttonPanel.add(stopButton);
        // 将按钮面板放入一个 JScrollPane
        JScrollPane buttonScrollPane = new JScrollPane(buttonPanel);

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane(responseTextArea), BorderLayout.CENTER);
        getContentPane().add(buttonScrollPane, BorderLayout.SOUTH);

        getContentPane().add(panel, BorderLayout.NORTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //pack();  // 自动调整窗口大小以适应组件
        setLocationRelativeTo(null);  // 将窗口放置在屏幕中央

        setSize(1000, 600);
        setLocationRelativeTo(null);

        // Set default values
        kafkaServerField.setText("127.0.0.1:9092");
        connectCountField.setText("3");
        waitingTimeField.setText("10");

    }

    private int[] sendGetRequest() {
        int[] intArray = new int[5];
        try {
            // Replace "YOUR_API_ENDPOINT" with the actual URL you want to send the GET request to
            String apiUrl = "http://localhost:8080/api/kafka/checkout";
            URL url = new URL(apiUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String response = reader.readLine();
                reader.close();

                // Assuming the server returns a comma-separated string of integers
                String[] intStrings = response.substring(1, response.length() - 1).split(",");//返回的是字符串形式的int[],如[1,2,3,4]，需要把括号去掉再进行分割。请求接收都是以字符串形式进行。
                for (int i = 0; i < intStrings.length; i++){
                    System.out.println(intStrings[i].toString());
                }
                for (int i = 0; i < intStrings.length; i++) {
                    intArray[i] = Integer.parseInt(intStrings[i]);
                }
                intArray[4]=1;
            } else {
                responseTextArea.append("agent未启动！"+ "\n");
                intArray[4]=0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return intArray;
    }
    private void check(){
        int[] checkarray=sendGetRequest();
        //int tryCount =checkarray[0];
        int tryCount =1;
        int connectCount =checkarray[1];
        int waitingTime=checkarray[2];
        intListeningActive = checkarray[3];

        if (checkarray[4]==0){
            System.out.println("agent未启动！");
            responseTextArea.append("agent未启动！"+ "\n");
        }
        else{
            responseTextArea.append("agent已经启动！" + "\n");
            responseTextArea.paintImmediately(responseTextArea.getBounds());

            responseTextArea.setCaretPosition(responseTextArea.getDocument().getLength());
            while (intListeningActive==0 && tryCount <= connectCount) {
                String s =String.format("正在尝试第%d连接",tryCount);
                responseTextArea.append(s + "\n");
                responseTextArea.paintImmediately(responseTextArea.getBounds());

                System.out.println(s);
                try {
                    // 休眠waitingTime秒
                    Thread.sleep(waitingTime * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 处理中断异常，如果需要的话
                }
                checkarray=sendGetRequest();//重新查询连接状况
                tryCount++;
                //tryCount =checkarray[0];
                //connectCount =checkarray[1];
                //waitingTime=checkarray[2];
                intListeningActive = checkarray[3];
            }
            if(intListeningActive==1) {
                // 将新的日志信息追加到JTextArea中
                responseTextArea.append("连接成功!" + "\n");

                // 强制滚动到文本区域的底部，以便查看最新的日志信息，不能即使渲染，需要使光标强制转到文本末，再加上其他信息。
                responseTextArea.setCaretPosition(responseTextArea.getDocument().getLength());
                this.setExtendedState(JFrame.ICONIFIED);//this指向当前jframe对象，最小化窗口
                ImageIcon activeIcon = new ImageIcon("./demo/src/main/resources/static/image/success.jpg");
                this.setIconImage(activeIcon.getImage());

            }else {
                responseTextArea.append("未连接成功，已超过重复连接次数！"+ "\n");
                responseTextArea.setCaretPosition(responseTextArea.getDocument().getLength());
                ImageIcon inactiveIcon = new ImageIcon("./demo/src/main/resources/static/image/fail.jpg");
                this.setIconImage(inactiveIcon.getImage());
            }
            //需要程序执行完毕之后才会把信息展示到textarea
        }
    }
    private void stop(){
        try {
            // Replace "YOUR_API_ENDPOINT" with the actual URL you want to send the GET request to
            String apiUrl = "http://localhost:8080/api/kafka/stoplistening";
            URL url = new URL(apiUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取输入流
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String response = reader.readLine();

                    // 解析布尔值,点击之后返回false，代表关闭了
                    boolean stopListening = Boolean.parseBoolean(response);

                    // 根据返回的布尔值执行相应的逻辑
                    if (stopListening) {
                        responseTextArea.append("未关闭连接！"+ "\n");
                        intListeningActive=1;
                    } else {
                        responseTextArea.append("已关闭连接！"+ "\n");
                        intListeningActive=0;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    // 处理读取输入流时的异常
                }
            } else {
                responseTextArea.append("agent未启动！"+ "\n");
            }
        } catch (Exception e) {
            responseTextArea.append("agent未启动！"+ "\n");

            e.printStackTrace();
        }
    }
    private void saveYaml() {
        // Get values from text fields
        String kafkaServer = kafkaServerField.getText();
        String connectCount = connectCountField.getText();
        String waitingTime = waitingTimeField.getText();

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("./demo/src/main/resources/application.yml",false))) {
            // Convert YAML content to a YAML-formatted string
            String yamlString = "my-app:\n" +
                    "  kafka-server: " + kafkaServer + "\n" +
                    "  connect-count: " + connectCount + "\n" +
                    "  waiting-time: " + waitingTime + "\n";

            // Write the string to the file
            writer.write(yamlString);
            JOptionPane.showMessageDialog(this, "保存成功", "Success", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "保存失败", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    //添加托盘显示：1.先判断当前平台是否支持托盘显示
    public void setTray(){
        if(SystemTray.isSupported()){//判断当前平台是否支持托盘功能
            Image image = setImage(intListeningActive);
            ActionListener listener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Show();
                }
            };
            // 创建弹出菜单
            PopupMenu popup = new PopupMenu();
            //主界面选项
            MenuItem mainFrameItem = new MenuItem("主界面");
            mainFrameItem.addActionListener(listener);

            // 添加一个新的选项，弹出对话框
            MenuItem settingsItem = new MenuItem("配置");
            settingsItem.addActionListener(e -> {
                showSettingsDialog();
            });
            //退出程序选项
            MenuItem exitItem = new MenuItem("退出");
            exitItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "确认退出") == 0) {
                        System.exit(0);
                    }
                }
            });

            popup.add(mainFrameItem);
            popup.add(settingsItem);
            popup.add(exitItem);
            trayIcon = new TrayIcon(image, "ItestAgent", popup);// 创建trayIcon
            this.setIconImage(trayIcon.getImage());//同时更改任务栏jframe图标
            trayIcon.addActionListener(listener);

            // 从 SystemTray 中移除原有的 TrayIcon
            for (TrayIcon existingTrayIcon : tray.getTrayIcons()) {
                tray.remove(existingTrayIcon);
            }
            try {
                tray.add(trayIcon);
            } catch (AWTException e1) {
                e1.printStackTrace();
            }
        }
        else {
            System.out.println("当前系统不支持托盘功能");
            Image image = setImage(intListeningActive);
            this.setIconImage(image);//更改任务栏jframe图标
        }
    }
    private Image setImage(int intListeningActive){
        if (intListeningActive == 1) {
            return Toolkit.getDefaultToolkit().getImage("./demo/src/main/resources/static/image/success_thumbnail.jpg");
        }
        return Toolkit.getDefaultToolkit().getImage("./demo/src/main/resources/static/image/fail_thumbnail.jpg");
    }
    private void showSettingsDialog() {
        // Create layout for settings dialog
        JPanel settingsPanel = new JPanel(new GridLayout(4, 2));
        settingsPanel.add(new JLabel("服务器ip及端口"));
        settingsPanel.add(kafkaServerField);
        settingsPanel.add(new JLabel("重新连接次数"));
        settingsPanel.add(connectCountField);
        settingsPanel.add(new JLabel("连接等待时间/s"));
        settingsPanel.add(waitingTimeField);

        // Show dialog
        int result = JOptionPane.showConfirmDialog(this, settingsPanel, "配置", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            saveYaml();
        }
    }
    //内部类中不方便直接调用外部类的实例（this不能指向）
    public void UnVisible() {
        this.setVisible(false);
    }
    public void Show() {
        this.setVisible(true);
    }
    public void Exit() {
        System.exit(0);
    }
    public static void main(String[] args) {
        Swing swingApp = new Swing();
        swingApp.setVisible(true);
    }

}
